package prodconsume;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Slf4j
public class ProdConsumeDemo {

    static class Bakery {
        List<Bread> breads = new ArrayList<>();

        final Integer maxCapacity = 10;

        public void put(Bread bread) throws InterruptedException {
            synchronized (breads) {
                while(breads.size() == maxCapacity) {
                    log("array is full");
                    breads.wait();
                }
                breads.add(bread);
                breads.notifyAll();
            }
        }

        public Bread get() throws InterruptedException {
            Bread bread = null;
            synchronized (breads) {
                while(breads.isEmpty()) {
                    log("array is empty");
                    breads.wait();
                }
                bread = breads.remove(breads.size()-1);
                breads.notifyAll();
            }
            return bread;
        }

        private void log(String message) {
            log.info(message);
        }
    }



    static class Bread {
    }

    public static void main(String[] args) {
        Bakery bakery = new Bakery();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Random random = new Random();
        executorService.submit(() -> {
            while(true) {
                try {
                    bakery.put(new Bread());
                    int addition = 0;
                    int time = random.nextInt(500);
                    // log.info("producer,to sleep:{} millis", time);
                    Thread.sleep(time);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        executorService.submit(() -> {
            while(true) {
                try {
                    int time = random.nextInt(2000);
                    // log.info("consumer,to sleep:{} millis", time);
                    Thread.sleep(time);
                    bakery.get();

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
